package com.rhb.af.web.util;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.rhb.af.web.bean.Menu;

public class MenuDefinition {
	public static Map prase(String filePath) {
		File file = new File(filePath);
		SAXReader reader = new SAXReader();
		Map menus = new HashMap();
		try {
			Document doc = reader.read(file);
			Element root = doc.getRootElement();
			for (Iterator i = root.elementIterator(); i.hasNext();) {
				Element e = (Element) i.next();
				Menu menu = new Menu();
				setAttribute(menu, e);
				menus.put(menu.getName(), menu);
			}
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		return menus;
	}

	private static void setAttribute(Object obj, Element element) {
		for (Iterator i = element.attributeIterator(); i.hasNext();) {
			Attribute a = (Attribute) i.next();
			try {
				BeanUtils.setProperty(obj, a.getName(), a.getValue());
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			}
		}
	}
}
